import styles from './Detail.module.scss'
import Drawer from '@renderer/components/drawer'

import { getGroupChatNoticeDetail, getGroupChatNoticeDetailList, exportGroupChatNoticeDetail } from '@renderer/ajax/api/publishGroupNotice'
import { defineComponent, reactive, watch } from 'vue'
import dayjs from 'dayjs'
import { useExpose } from '@renderer/utils'
import { ElMessage, ElTable, ElTableColumn, ElImage, ElIcon, ElEmpty, ElTooltip, ElForm, ElFormItem, ElSelect, ElRow, ElCol, ElOption, ElInput, ElButton, ElDescriptions, ElDescriptionsItem, ElPagination, ElScrollbar } from 'element-plus'
import { QuestionFilled } from '@element-plus/icons-vue'
import { toBuffer } from '@renderer/utils/utils'
import ZWGroupAvatar from '@renderer/components/win/ZWSelectGroup/ZWGroupAvatar.vue'
const { ipcRenderer } = require("electron");
const fs = require('fs')

export default defineComponent({
    name: 'PublishGroupNoticeDetail',
    setup(props, { emit, slots }) {
        const drawerData = reactive({
            visible: false,
            title: '活动标题',
            width: '860px'
        })
        const state = reactive({
            row: {},
            list: [],
            params: {
                Id: '',
                Title: '',
                Status: 0,
                page: 1,
                pageSize: 15,
            },
            total: 0,
            Phone: '',
            StatusOption: [
                { name: '全部状态', id: 0 },
                { name: '发布成功', id: 2 },
                { name: '发布失败', id: 3 },
                { name: '等待发布', id: 1 }
            ],
            Data: {
                id: '',
                title: '',
                custGroupList: [],
                specifySendTime: null,
                notice: '',
                status: '',
                isAllGroupChat: false,
                createdAt: ''
            }
        })
        // 导出
        const onExport = async () => {
            const res: any = await exportGroupChatNoticeDetail(state.params)
            let params = {
                title: '请选择下载文件的目录',
                buttonLabel: '保存',
                pathName: `${state.Data.title || ''}_${dayjs(state.Data.createdAt).format('YYYY_MM_DD')}.xlsx`,
            }
            let buf = toBuffer(res)
            ipcRenderer.invoke("open-savebox", params).then((res) => {
                fs.writeFileSync(res.filePath, buf)
                res && ElMessage.success('导出成功')
            });
        }

        const onState = async (row: any) => {
            drawerData.visible = true
            state.row = row
            state.params.Id = row.Id
            const res: any = await Promise.allSettled([
                getGroupChatNoticeDetail({ Id: row.Id }),
                getGroupChatNoticeDetailList({ ...state.params, Id: row.Id, Title: state.params.Title, Status: state.params.Status })
            ])

            const [dataRes, listRes] = res
            if (dataRes.status === "fulfilled") {
                state.Data = dataRes.value
                drawerData.title = `${dataRes.value.title} (${renderStatus()})`
            }

            if (listRes.status === "fulfilled") {
                state.list = listRes.value.data
                state.total = listRes.value.total
            }
        }
        // 获取列表
        const getList = async () => {
            console.log('state.params: ', state.params);
            const res: any = await getGroupChatNoticeDetailList(state.params)
            state.list = res.data
            state.total = res.total
        }

        // 搜索
        let timeout: any
        const onSearch = () => {
            if (timeout) clearTimeout(timeout)
            timeout = setTimeout(() => {
                getList()
            }, 400)
        }
        const onSizeChange = (v: number) => {
            state.params.pageSize = v
            getList()
        }
        const onCurrentChange = (v: number) => {
            state.params.page = v
            getList()
        }
        let timer: any = null
        // 开启定时器
        const startTimer = () => {
            timer = setInterval(() => {
                onState(state.row)
            }, 5000)
        }
        // 关闭定时器
        const closeTime = () => {
            clearInterval(timer)
            state.list = []
            state.params.Id = ''
            state.params.Title = ''
            state.params.Status = 0
            state.params.page = 1
            state.params.pageSize = 15
        }
        watch(
            () => drawerData.visible,
            (v) => (v ? startTimer() : closeTime())
        )
        useExpose({
            onState
        })

        const renderError = (statusMsg, msg) => {
            return (
                <>
                    <div class={styles.error}>
                        {statusMsg}
                        {
                            msg ? <ElTooltip effect="dark" content={msg} placement="top">
                                <ElIcon>
                                    <QuestionFilled />
                                </ElIcon>
                            </ElTooltip> : ''
                        }
                    </div>
                </>
            )
        }
        // 渲染群聊个数
        const renderGroup = () => {
            if(state.Data.isAllGroupChat) {
                return <div>全部群聊(共{state.Data.custGroupList?.length}个群聊)</div>
            } else {
                return <div>筛选群聊(共{state.Data.custGroupList?.length}个群聊)</div>
            }
        }

        // 渲染群公告
        const renderNotice = ()  => {
            return <ElTooltip effect="dark" popperStyle={{
                maxWidth: '300px',
            }} disabled={state.Data.notice.length <= 200} placement="top">
                {{
                    default: () => <div>{state.Data.notice.length > 200 ?
                        <span>{state.Data.notice.slice(0, 200)}...</span>
                        : state.Data.notice || '--'}</div>,
                    content: () => <ElScrollbar maxHeight={300}>
                        {state.Data.notice}
                    </ElScrollbar>
                }}
            </ElTooltip>
        }
        const renderStatus = () => {
            const arr = ['', '未开始', '进行中', '已暂停', '已完成']
            return arr[state.Data?.status]
        }
        const renderInfo = (row: any) => (
            <div class={styles.column_info}>
                <ZWGroupAvatar avatars={row.groupChatInfo?.avatars} ></ZWGroupAvatar>
                <div class={styles.column_info_name}>{row.groupChatInfo?.name}</div>
            </div>
        )
        return () => (
            <>
                <Drawer state={drawerData}>
                    {{
                        default: () => (
                            <div class={styles.drawer_content}>
                                <div class={styles.info}>
                                    <ElDescriptions column={1}>
                                        <ElDescriptionsItem label="企微群：">
                                            {renderGroup()}
                                        </ElDescriptionsItem>
                                        <ElDescriptionsItem label="发送方式：" >
                                            {state.Data.specifySendTime || '立即发送'}
                                        </ElDescriptionsItem>
                                        <ElDescriptionsItem label="群公告：">
                                            {renderNotice()}
                                        </ElDescriptionsItem>
                                        <ElDescriptionsItem label="创建时间：">
                                            {state.Data.createdAt || '--'}
                                        </ElDescriptionsItem>
                                    </ElDescriptions>
                                </div>
                                <ElForm inline={true}>
                                    <ElRow>
                                        <ElCol span={10}>
                                            <ElFormItem label="群名称" style="margin:0 10px 0 0">
                                                <ElInput style="width:100%" vModel={state.params.Title} onInput={onSearch} clearable placeholder="请输入群名称进行搜索" />
                                            </ElFormItem>
                                        </ElCol>
                                        <ElCol span={10}>
                                            <ElFormItem label="发布状态" style="margin:0 10px 0 0">
                                                <ElSelect
                                                    style="width:100%"
                                                    vModel={state.params.Status}
                                                    placeholder="请选择"
                                                    onChange={getList}
                                                    vSlots={{
                                                        default: () => (
                                                            <>
                                                                {state.StatusOption.map((item) => (
                                                                    <ElOption key={item.id} label={item.name} value={item.id} />
                                                                ))}
                                                            </>
                                                        )
                                                    }}
                                                />
                                            </ElFormItem>
                                        </ElCol>
                                        <ElCol span={4}>
                                            <div style="text-align: right;">
                                                <ElButton type="primary" onClick={onExport}>
                                                    导出
                                                </ElButton>
                                            </div>
                                        </ElCol>
                                    </ElRow>
                                    <ElRow>
                                        <ElCol span={12}></ElCol>
                                    </ElRow>
                                </ElForm>
                                <div class={styles.table}>
                                    <ElTable
                                        data={state.list}
                                        maxHeight={600}
                                        vSlots={{
                                            default: () => (
                                                <>
                                                    <ElTableColumn label="群信息" minWidth="120" vSlots={{ default: ({ row }) => renderInfo(row) }} />
                                                    <ElTableColumn label="发布时间" minWidth="170" prop="CreatedAt" vSlots={{ default: ({ row }) => row.sendTime || '--' }} />
                                                    <ElTableColumn label="发布状态" minWidth="120" vSlots={{ default: ({ row }) => renderError(row.sendStatusMsg, row.errorMsg) }} />
                                                </>
                                            ),
                                            empty: () => <ElEmpty />
                                        }}
                                    />
                                    <ElPagination
                                        class={styles.pagination}
                                        vModel:currentPage={state.params.page}
                                        vModel:pageSize={state.params.pageSize}
                                        page-sizes={[15, 30, 50, 100]}
                                        background
                                        layout="total,  prev, pager, next,sizes, jumper"
                                        total={state.total}
                                        onSizeChange={onSizeChange}
                                        onCurrentChange={onCurrentChange}
                                    />
                                </div>
                            </div>
                        )
                    }}
                </Drawer>
            </>
        )
    }
})
